package com.zjmzxfzhl.modules.purchase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zjmzxfzhl.common.base.BaseServiceImpl;
import com.zjmzxfzhl.common.exception.AppException;
import com.zjmzxfzhl.common.util.PathUtil;
import com.zjmzxfzhl.common.util.bs.PurchaseUtils;
import com.zjmzxfzhl.modules.purchase.controller.dto.PurchaseOrderDetailDto;
import com.zjmzxfzhl.modules.purchase.controller.vo.PurchaseOrderDetailVo;
import com.zjmzxfzhl.modules.purchase.entity.PurchaseFile;
import com.zjmzxfzhl.modules.purchase.entity.PurchaseOrderDetail;
import com.zjmzxfzhl.modules.purchase.entity.PurchaseSupplier;
import com.zjmzxfzhl.modules.purchase.mapper.PurchaseFileMapper;
import com.zjmzxfzhl.modules.purchase.mapper.PurchaseOrderDetailMapper;
import com.zjmzxfzhl.modules.purchase.mapper.PurchaseSupplierMapper;
import com.zjmzxfzhl.modules.purchase.service.PurchaseOrderDetailService;
import com.zjmzxfzhl.modules.purchase.service.PurchaseSupplierService;
import com.zjmzxfzhl.modules.purchase.service.bo.PurchaseSupplierDetailExcelBo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Service
 *
 * @author 庄金明
 */
@Service
public class PurchaseSupplierServiceImpl extends BaseServiceImpl<PurchaseSupplierMapper, PurchaseSupplier>
        implements PurchaseSupplierService {
    @Autowired
    private PurchaseOrderDetailService detailService;

    @Autowired
    private PurchaseFileMapper purchaseFileMapper;

    @Autowired
    private PurchaseOrderDetailMapper detailMapper;

    @Override
    public IPage<PurchaseSupplier> list(IPage<PurchaseSupplier> page, PurchaseSupplier purchaseSupplier) {
        return page.setRecords(baseMapper.list(page, purchaseSupplier));
    }

    @Override
    public PurchaseSupplier validPurchaseSupplier(PurchaseSupplier supplier) {
        if (!StringUtils.isEmpty(supplier.getSupplierName())) {
            PurchaseSupplier filter = new PurchaseSupplier();
            filter.setSupplierName(supplier.getSupplierName());
            List<PurchaseSupplier> dbSuppliers = this.list(new QueryWrapper<>(filter));
            if (CollectionUtils.isEmpty(dbSuppliers)) {
                this.save(supplier);
                return supplier;
            }
            return dbSuppliers.get(0);
        } else {
            throw new AppException("审批单缺少供应商名称");
        }
    }

    @Override
    public void deleteSuppliers(List<Long> ids) {
        for (Long supplierId : ids) {
            PurchaseOrderDetail filter = new PurchaseOrderDetail();
            filter.setSupplierId(supplierId);
            List<PurchaseOrderDetail> details = detailService.list(new QueryWrapper<>(filter));
            if (!CollectionUtils.isEmpty(details)) {
                throw new AppException("存在关联的审批单：" + details.get(0).getOrderId());
            }
        }
        this.removeByIds(ids);
    }


    @Override
    public File exportDetail(Long supplierId, String startDate, String endDate) {
        //查询所有相关内容
        PurchaseSupplier supplier = this.getById(supplierId);
        PurchaseOrderDetailDto filter = new PurchaseOrderDetailDto();
        filter.setSupplierId(supplierId);
        if (!StringUtils.isEmpty(startDate)) {
            filter.setStartDate(startDate);
        }
        if (!StringUtils.isEmpty(endDate)) {
            filter.setEndDate(endDate);
        }
        List<PurchaseOrderDetailVo> orderDetails = detailService.listBy(filter);
        List<PurchaseSupplierDetailExcelBo> excelBos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderDetails)) {
            for (PurchaseOrderDetailVo detailVo : orderDetails) {
                PurchaseSupplierDetailExcelBo excelBo = new PurchaseSupplierDetailExcelBo(detailVo);
                excelBos.add(excelBo);
            }

        }
        File exportFile = null;
        try {
            ClassPathResource templateFileResource = new ClassPathResource("templates/supplier-template.xls");
            exportFile = PathUtil.getTempFile(supplier.getSupplierName() + "_.xls");
            FileUtils.copyInputStreamToFile(templateFileResource.getInputStream(), exportFile);
            PurchaseUtils.exportPurchaseSupplier(startDate, endDate, excelBos, exportFile);
        } catch (Exception e) {
            throw new AppException("文件读取失败" + e.getMessage());
        }
        return exportFile;

    }

    @Override
    public boolean mergeSupplier() {
        //找到同名厂家
        List<String> supplierNames = this.baseMapper.findSameSupplierName();
        if (!CollectionUtils.isEmpty(supplierNames)) {
            for (String supplierName : supplierNames) {
                disposeSameSupplier(supplierName);
            }
        }
        return true;
    }

    public void disposeSameSupplier(String supplierName) {
        PurchaseSupplier filter = new PurchaseSupplier();
        filter.setSupplierName(supplierName);
        List<PurchaseSupplier> dbSuppliers = this.list(new QueryWrapper<>(filter));
        if (dbSuppliers.size() > 1) {
            Long tgtId = dbSuppliers.get(0).getId();
            for (int i = 1; i < dbSuppliers.size(); i++) {
                Long supplierId = dbSuppliers.get(i).getId();
                //替换 supplier id
                replaceSupplierId(supplierId, tgtId);
                //删除 多余supplier
                this.removeById(supplierId);
            }
        }
    }

    @Override
    public void replaceSupplierId(Long oId, Long nId) {
        PurchaseFile fileFilter = new PurchaseFile();
        fileFilter.setSupplierId(oId);
        List<PurchaseFile> purchaseFiles = purchaseFileMapper.selectList(new QueryWrapper<>(fileFilter));
        if (!CollectionUtils.isEmpty(purchaseFiles)) {
            for (PurchaseFile purchaseFile : purchaseFiles) {
                purchaseFile.setSupplierId(nId);
                this.purchaseFileMapper.updateById(purchaseFile);
            }
        }

        PurchaseOrderDetail detailFilter = new PurchaseOrderDetail();
        detailFilter.setSupplierId(oId);
        List<PurchaseOrderDetail> details = detailMapper.selectList(new QueryWrapper<>(detailFilter));
        if (!CollectionUtils.isEmpty(details)) {
            for (PurchaseOrderDetail detail : details) {
                detail.setSupplierId(nId);
                this.detailMapper.updateById(detail);
            }
        }
    }

    @Override
    public void replaceSuppliers(List<Long> oids, Long nid) {
        for (Long oid : oids) {
            this.replaceSupplierId(oid, nid);
            //删除 多余supplier
            this.removeById(oid);
        }
    }
}
